const request = require('request');

exports.main = async (event, context) => {
  const { location } = event
  return new Promise(resolve => {
    if (location == null || location == "") {
      return resolve("缺少必要参数:location")
    }
    if (!process.env.MAPKEY){
      return resolve("未配置环境变量：MAPKEY")
    }
    geocoder(location, resolve);
  })
}

async function geocoder(location, callback) {
  const url = `https://restapi.amap.com/v3/geocode/regeo?location=${location}&key=${process.env.MAPKEY}`;
  request(url, function (error, response, body) {
    let code = response.statusCode.toString(), result = null
    if (code == '200') {
      let res = JSON.parse(body);
      if (res.status == "1" && res.info == "OK") {
        result = res.regeocode;
      } else {
        console.error(res)
      }
    }
    callback && callback(result);
  });
}